The goal of this lab is to explore various ways of building maps with ggplot2.
Challenges are not mandatory for students to complete. We highly recommend students attempt them though. We would expect graduate students to attempt the challenges.
Datasets
We’ll be using the US_income.rda dataset which should be placed in the /data subdirectory in our data_vis_labs project. You’ll also be downloading your own data to build maps.
Make a county map of a US state using geom_polygon(). Maybe use your home state or a favorite state. Please do NOT use the state in the ggplot2 book example.
Optional: Consider adding major cities (or your home town).
ga_counties <-map_data("county", "georgia") %>%select(lon = long, lat, group, id=subregion)ga_cities <-places(state ="GA", class ="data.frame")#geom_sf_text(ga_cities, mapping = aes(label = city)) ggplot(ga_counties, aes(lon,lat))+geom_polygon(aes(group = group),fill =NA, color ="grey50")+coord_quickmap() +ggtitle("Georgia") +theme_void()
Plot 2
Now use geom_sf() instead. You’ll need to download data for this. You can use either the tigris (github page) or geodata packages. Either tigris’ counties() with cb = TRUE or geodata’s gadm() could be useful.
Solution
Code
#using Tigris ga_data <-counties(state ="GA", cb=TRUE, progress_bar =FALSE) #prevent function from showing progress barggplot(ga_data) +geom_sf(fill =NA)+theme_void() +ggtitle("Georgia" )
viridis package (discrete = TRUE in scale_* function)
Statebins theme
Solution
Code
ggplot(US_income, aes(state = name, fill = income_bins))+geom_statebins() +scale_fill_viridis(discrete =TRUE)+theme_statebins()+labs(fill ="Median\nIncome")
Exercise 3
Pick any city or foreign country to build a map for. You can dress it up or make it as basic as you want. Also welcome to try building a graphic like that depicted at the end of section 6.5 — use a different region though.
It is optional for everyone, but we highly encourage students to give it a try. Several students in past versions of this course used mapping data like this for their final project. Usually using the leaflet or mapview packages. This one is done with mapview, but as an additional challenge students could try doing this with leaflet too.
Using the tidycensus package and few others, try to create a map like below using these directions. Try using a different geographical area and a different variable from the ACS.
Solution
Code
options(tigris_use_cache =TRUE)#get ACS data for Fulton County, GAatlanta <-get_acs(state ="GA",county ="Fulton",geography ="tract",variables ="B27001_001",geometry =TRUE,year =2020)pal <-colorNumeric(palette ="viridis",domain = atlanta$estimate,na.color ="transparent")leaflet(data=atlanta) %>%addTiles() %>%addPolygons(fillColor =~pal(estimate),color ="black",weight =1, opacity =1, fillOpacity =0.7,popup =~paste("Estimate:", estimate)) %>%addLegend(pal = pal,values =~estimate,opacity=0.7,title ="Population with Health Insurance",position ="bottomright" )